export default {
    init(cb) {
        const errorfn = window.onerror
        window.onerror = function (message, source, lineno, colno, error) {
            const errorInfo = callbackError(error)
            errorInfo.type = 'error'
            cb(errorInfo)
            errorfn && errorfn.apply(window, arguments)
        }

        window.onunhandledrejection = e => {
            if (e && e.reason) {
                cb({ errorType: e.type || 'unhandledrejection', reason: e.reason })
            }
        }

        window.addEventListener('error', function(event) {
            let target = event.target
            if (target && target.baseURI) {
                cb({
                    message: target.outerHTML, 
                    url: target.baseURI,
                    errorType: 'resource'
                })
            }
        }, true)

    }
}

function callbackError(errorObj) {
    // 浏览器兼容
    let col = errorObj.column || errorObj, columnNumber
    let row = errorObj.line || errorObj, lineNumber
    let errorType = errorObj.name
    let message = errorObj.message
    let { stack } = errorObj
    let stackCol = null
    let stackRow = null
    let url = ''
    if (stack) {
        let matcher = stack.match(/https?:\/\/[^\n]+/)
        let firstStack = matcher ? matcher[0] : ''
        let regCheck = /https?:\/\/(\S)*\/\.js?/
        if (regCheck.test(firstStack)) {
            url = firstStack.match(regCheck)[0]
        }
        let postStack = firstStack.match(/:(\d+):(\d+)/)
        if (postStack && postStack.length >= 3) {
            [, stackCol, stackRow] = postStack
        }
    }
    return {
        content: stack,
        col: Number(stackCol || col),
        row: Number(stackRow || row),
        errorType, message, url
    }
}
